package be.nvlooy.moviereminder.service.implementations;

import be.nvlooy.moviereminder.dto.ReleaseDateMovieDTO;
import be.nvlooy.moviereminder.service.ReleaseDateService;
import com.amazon.commerce.model.*;
import com.amazon.commerce.service.AwsGateway;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: Nik Van Looy
 * @since: 19/09/11
 */
@Service
@Scope("singleton")
public class AmazonReleaseDateServiceImpl implements ReleaseDateService {

    private AwsGateway awsGateway;

    @Autowired
    public void setAwsGateway(AwsGateway awsGateway) {
        this.awsGateway = awsGateway;
    }

    @Override
    public List<ReleaseDateMovieDTO> findMoviesByTitle(String movieTitle) {
        ItemSearchRequest searchRequest;
        ItemSearchResponse searchResponse;
        List<Items> itemsList;
        List<ReleaseDateMovieDTO> result = new ArrayList<ReleaseDateMovieDTO>();

        searchRequest = new ItemSearchRequest();
        searchRequest.setSearchIndex("All");
        searchRequest.setTitle(movieTitle);

        // Response Groups
        searchRequest.getResponseGroup().add("ItemAttributes");
        searchResponse = awsGateway.search(searchRequest);
        itemsList = searchResponse.getItems();

        // convert Amazon items to DTO's
        for(Items amzonItemsList : itemsList) {
            List<Item> amazonItems = amzonItemsList.getItem();

            for(Item amazonItem : amazonItems) {
                // now we only add movies
                if("DVD".equals(amazonItem.getItemAttributes().getProductGroup())) {
                    result.add(convertDto(amazonItem));
                }
            }
        }

        return result;
    }

    private ReleaseDateMovieDTO convertDto(Item amazonItem) {
        ReleaseDateMovieDTO dto = new ReleaseDateMovieDTO();
        ItemAttributes itemAttributes = amazonItem.getItemAttributes();
        dto.setName(itemAttributes.getTitle());
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dto.setReleasedDate(format.parse(itemAttributes.getReleaseDate()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return dto;
    }
}
